package com.shu.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;

import com.shu.service.SysRoleAuthorityService;

@Component
public class MyFilterSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

	
	private static Log logger = LogFactory.getLog(MyFilterSecurityMetadataSource.class);

    private static HashMap<String, List<String>> allResourceRole = new HashMap<String, List<String>>();
    
    // 所有URL对应的角色，得到的结果是：不同的URL下，包含的多个角色
    @Resource
    private SysRoleAuthorityService roleAuthorityService;
    
    @PostConstruct
    private void loadResource() {
    	loadAllRoleAuthority();
    }
    
    
    
    /**
     * 加载数据库中所有角色权限列表
     * 资源为key， 权限为value。 资源通常为url， 权限就是那些以ROLE_为前缀的角色。 一个资源可以由多个权限来访问。
     */
    private void loadAllRoleAuthority() {
    	allResourceRole.clear();
    	allResourceRole.putAll(roleAuthorityService.getALlRoleAuthority());
    	logger.info("loadAllRoleAuthority:"+allResourceRole);
    }
    
    public List<ConfigAttribute> getAttributes(Object object) {
        FilterInvocation fi = (FilterInvocation) object;
        String requestUrl = fi.getRequest().getRequestURI();
        String projectName = fi.getRequest().getContextPath();
        List<ConfigAttribute> attributes = new ArrayList<ConfigAttribute>();
        for (Entry<String, List<String>> ent : allResourceRole.entrySet()) {
            String url = ent.getKey();
            List<String> rolesList = ent.getValue();
            //根据业务写自己的匹配逻辑
            if(requestUrl.startsWith(projectName+url)){
                attributes.addAll(SecurityConfig.createListFromCommaDelimitedString(String.join(",", rolesList)));
            }
        }
        logger.info("requestUrl["+requestUrl+"]need roles "+attributes);
        return attributes.isEmpty()?null:attributes;
    }


    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    public boolean supports(Class<?> clazz) {
        return FilterInvocation.class.isAssignableFrom(clazz);
    }
    
	public SysRoleAuthorityService getRoleAuthorityService() {
		return roleAuthorityService;
	}

	public void setRoleAuthorityService(SysRoleAuthorityService roleAuthorityService) {
		this.roleAuthorityService = roleAuthorityService;
	}
    
}	